package com.learn.chain.second;
import java.util.List;

public class RealInterceptorChain implements Interceptor.Chain {

    private int index;
    private List<Interceptor> interceptors;
    private Request request;

    public RealInterceptorChain(List<Interceptor> interceptors, int index, Request request) {
        this.interceptors = interceptors;
        this.index = index;
        this.request = request;
    }

    @Override
    public Request request() {
        return this.request;
    }

    @Override
    public Response proceed(Request request) {
        if (index >= interceptors.size()) throw new Error("当前索引和拦截器长度不配");
        // 得到下一个责任链拦截器，将index+1
        RealInterceptorChain next = new RealInterceptorChain(interceptors, index + 1, request);
        // 获取当前拦截器
        Interceptor interceptor = interceptors.get(index);
        // 执行拦截方法，并把下一个拦截器传递
        Response response = interceptor.intercept(next);
        return response;
    }
}
